<template>
    <div>
        <Card :bordered="false" dis-hover class="ivu-mt">
            <jg-Search :searchData="searchData" @on-enter="askDatasearch" @on-clear="askDatasearch"
                v-on:click-click="handleAllocation()"></jg-Search>
            <Table highlight-row size="small" :loading="tableLoading" :columns="columns" :data="data" class="ivu-mt-16">
                <template slot-scope="{ row }" slot="status">
                    <Button v-if="row.status === '1'" type="success" size="small">启用</Button>
                    <Button v-if="row.status === '0'" type="error" size="small">停用</Button>
                </template>
                <template slot-scope="{ row }" slot="operation">
                    <a v-hasC="{
                            name: 'base-tags-update',
                            flag: 'v1/base/tags/update',
                        }" :disabled="+row.is_inhibit_delete === 1" @click="handleAllocation(row)">编辑</a>
                    <Divider type="vertical" v-hasC="{
                            name: 'v1-base-tags-delete-tags-group',
                            flag: 'v1/base/tags/delete-tags-group',
                        }" />
                    <a v-hasC="{
                            name: 'v1-base-tags-delete-tags-group',
                            flag: 'v1/base/tags/delete-tags-group',
                        }" :disabled="+row.is_inhibit_delete === 1" @click="deleteTag(row)">删除</a>
                </template>
            </Table>
            <div class="ivu-mt ivu-text-center">
                <Page show-total show-elevator show-sizer :total="total" :current.sync="params.page"
                    :page-size="params.pageSize" :page-size-opts="pageOpts" @on-change="changepage"
                    @on-page-size-change="changepageSize" />
            </div>
        </Card>
        <Modal v-model="modal" :title="edit ? '编辑' : '新增'" :mask-closable="false" @on-cancel="handleDrawerCancel()">
            <Form :model="formItem" :rules="ruleValidate" ref="formItem" :label-width="118">
                <FormItem label="标签组名称" prop="input">
                    <Input v-model="formItem.input" placeholder="请输入标签组名称" clearable></Input>
                </FormItem>
                <FormItem label="标签组排序" prop="sort">
                    <Input v-model="formItem.sort" clearable></Input>
                </FormItem>
                <FormItem v-for="(item, inum) in formItem.items" :key="inum" :label="'标签 ' + item.index"
                    :prop="'items[' + inum + '].value'" :rules="{
                        required: true,
                        message: '标签 ' + item.index + ' 请录入内容',
                        trigger: 'blur',
                    }">
                    <Row>
                        <Col span="18">
                        <Input type="text" v-model="item.value" placeholder="输入子标签名称" clearable></Input>
                        </Col>
                        <Col span="4" offset="1">
                        <Button @click="
                                    handleRemove(item, formItem.items, inum)
                                ">删除</Button>
                        </Col>
                    </Row>
                </FormItem>
                <FormItem>
                    <Row>
                        <Col span="12">
                        <Button type="dashed" long @click="handleAdd" icon="md-add">新增标签</Button>
                        </Col>
                    </Row>
                </FormItem>
            </Form>
            <div slot="footer">
                <Button @click="handleDrawerCancel()">取消</Button>
                <Button type="primary" :loading="loading" @click="handleSubmit('formItem')">确定</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
    import {
        basetagsindex,
        basetagscreate,
        basetagsupdate,
        basetagstagsdel,
        deleteGroupTag,
    } from "@api/hqapi/indexone.js";
    import jgSearch from "@/components/search";
    import { mapState } from "vuex";

    export default {
        name: "diagnosis",
        components: { jgSearch },
        data() {
            const validateSort = (rule, value, callback) => {
                if (value !== "") {
                    if (!(/(^[0-9]\d*$)/.test(value))) {
                        callback(new Error('请输入正整数'));
                    } else {
                        callback();
                    }
                } else {
                    callback();
                }
            };
            return {
                searchData: {
                    project: [
                        {
                            key: "Input",
                            style: { width: "260px" },
                            value: "",
                            clearable: true,
                            placeholder: "请输入标签组或子标签名",
                        },
                    ],
                    button: [
                        {
                            key: "新增",
                            callback: "click",
                            has: {
                                name: "base-tags-create1",
                                flag: "v1/base/tags/create",
                            },
                        },
                    ],
                },
                index: 1,
                modal: false,
                edit: false,
                loading: false,
                tableLoading: false,
                deleteArr: [],
                formItem: {
                    input: "",
                    sort: "",
                    items: [
                        {
                            value: "",
                            index: 1,
                            have_bind: "",
                        },
                    ],
                },
                ruleValidate: {
                    input: [
                        {
                            required: true,
                            message: "标签组名不可为空",
                            trigger: "blur",
                        },
                    ],
                    sort: [
                        { validator: validateSort, trigger: 'blur' }
                    ],
                },
                columns: [
                    {
                        title: "标签组",
                        width: "180",
                        key: "group_name",
                    },
                    {
                        title: "排序",
                        width: "180",
                        key: "sort",
                    },
                    {
                        title: "子标签",
                        key: "tags_name",
                    },
                    {
                        title: "操作",
                        width: "120",

                        slot: "operation",
                    },
                ],
                params: { page: 1, pageSize: 10, type: 0, keywords: "" },
                total: 0,
                pageOpts: [10, 15, 20, 30, 50],
                data: [],
            };
        },
        created() {
            this.onLoad();
        },
        methods: {
            onLoad() {
                /**
                 * @description 标签列表 默认不传
                 * @param {Object} param page  {String} 页数
                 * @param {Object} param pageSize {String} 条数/页
                 */
                this.tableLoading = true;
                basetagsindex(this.params)
                    .then((res) => {
                        this.total = res.total;
                        this.data = res.list;
                        // console.log(1111)
                        // console.log(this.data)
                    })
                    .finally(() => {
                        this.tableLoading = false;
                    });
            },

            /* @函数功能: 分页 */
            changepage(e) {
                this.params.page = e;
                this.onLoad();
            },
            /* @函数功能: 每页数量 */
            changepageSize(e) {
                this.params.pageSize = e;
                this.onLoad();
            },
            askDatasearch() {
                this.params.keywords = this.searchData.project[0].value;
                this.onLoad();
            },
            handleAllocation(row) {
                this.modal = true;
                if (row) {
                    this.edit = true;
                    this.formItem = {
                        sort: row.sort,
                        input: row.group_name,
                        items: this.filteTags(row.tags_list),
                        id: row.id,
                    };
                    this.index = this.formItem.items.length;
                }
            },
            deleteTag(row) {
                this.$Modal.confirm({
                    title: "删除确认",
                    content:
                        "是否确定删除该标签组？删除了会自动清除患者身上对应的标签。",
                    loading: true,
                    onOk: () => {
                        deleteGroupTag({ id: row.id }).then((res) => {
                            this.$Modal.remove();
                            this.$Message.success("删除成功");
                            this.onLoad();
                        });
                    },
                });
            },
            filteTags(String) {
                let reArr = [];
                if (String) {
                    if (String && String.length > 0) {
                        String.forEach((item, inum) => {
                            reArr.push({
                                value: item.tags_name,
                                tags_id: item.id ? item.id : 0,
                                index: inum + 1,
                                have_bind: item.have_bind,
                            });
                        });
                    }
                }
                return reArr;
            },
            handleDrawerCancel() {
                this.modal = false;
                this.edit = false;
                this.index = 1;
                (this.formItem = {
                    input: "",
                    sort: "",
                    items: [
                        {
                            value: "",
                            index: 1,
                            have_bind: "",
                        },
                    ],
                }),
                    // this.onLoad();
                this.$refs.formItem.resetFields()
            },
            handleSubmit(name) {
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        this.loading = true;
                        const params = {
                            group_name: this.formItem.input,
                            type: 0,
                            sort: this.formItem.sort === "" ? 100 : this.formItem.sort,
                            list: JSON.stringify(
                                this.filterSubTags(this.formItem.items)
                            ),
                        };
                        if (this.edit) {
                            params.id = this.formItem.id;
                            this.updateSubmit(params);
                        } else {
                            this.createSubmit(params);
                        }
                    } else {
                        // console.log("表单校验失败！");
                    }
                });
            },
            filterSubTags(arr) {
                let reArr = [];
                if (arr && arr.length > 0) {
                    arr.forEach((item) => {
                        reArr.push({
                            tags_name: item.value,
                            tags_id: item.tags_id ? item.tags_id : 0,
                        });
                    });
                }
                return reArr;
            },
            handleAdd() {
                this.index++;
                this.formItem.items.push({
                    value: "",
                    index: this.index,
                });
            },
            handleRemove(item, items, inum) {
                this.logs(item, items, inum);
                if (+item.have_bind === 1) {
                    this.$Modal.confirm({
                        title: "删除标签",
                        content:
                            "<p>已有患者绑定该标签，是否确认删除？删除了会自动清除患者身上对应的标签。</p>",
                        onOk: () => {
                            this.formItem.items.splice(inum, 1);
                            this.index = this.formItem.items.length;
                        },
                    });
                } else {
                    this.formItem.items.splice(inum, 1);
                    this.index = this.formItem.items.length;
                }
            },
            // handleRemove(index, e, r) {
            //   if (this.formItem.items[r].have_bind === undefined||this.formItem.items[r].have_bind === '') {
            //     this.formItem.items.splice(r, 1);
            //     this.index = this.formItem.items.length;
            //   }
            //   if (index.have_bind === 1) {
            //     // if (this.index > 1) {
            //     //     basetagstagsdel({ tags_id: index.tags_id }).then(res => {
            //     //     })
            //     // } else {
            //     //     this.$Message.warning(' 至少录入一个子标签');
            //     // }
            //     basetagstagsdel({ tags_id: index.tags_id }).then(res => {
            //       this.formItem.items.splice(r, 1);
            //       this.index = this.formItem.items.length;
            //       this.$Message.info("删除成功");
            //     });
            //   } else if (index.have_bind === 0) {
            //     this.$Modal.confirm({
            //       title: "删除标签",
            //       content: "<p>已有患者绑定该标签，是否确认删除？删除了会自动清除患者身上对应的标签。</p>",
            //       onOk: () => {
            //         basetagstagsdel({ tags_id: index.tags_id }).then(res => {});
            //         this.formItem.items.splice(r, 1);
            //         this.index = this.formItem.items.length;
            //         this.$Message.info("删除成功");
            //       }
            //     });
            //   }
            // },
            filteReTags(arr) {
                let reArr = [];
                if (arr && arr.length > 0) {
                    arr.forEach((item, inum) => {
                        reArr.push({
                            value: item.value,
                            tags_id: item.tags_id ? item.tags_id : 0,
                            index: inum + 1,
                        });
                    });
                }
                return reArr;
            },
            createSubmit(params) {
                basetagscreate(params)
                    .then(() => {
                        this.$Message.success(" 创建成功");
                        this.onLoad();
                        this.handleDrawerCancel();
                    })
                    .finally(() => {
                        this.loading = false;
                    });
            },
            updateSubmit(params) {
                basetagsupdate(params)
                    .then(() => {
                        this.$Message.success(" 修改成功");
                        this.onLoad();
                        this.handleDrawerCancel();
                    })
                    .finally(() => {
                        this.loading = false;
                    });
            },
        },
    };
</script>